import { ref } from 'vue'
import { useWebSocketVue } from './websocket-service'
import type { UnifiedTaskMessage } from './websocket-service'

// 任务状态枚举
export enum TaskStatus {
  PENDING = 'PENDING',
  RUNNING = 'RUNNING',
  COMPLETED = 'COMPLETED',
  FAILED = 'FAILED',
  CANCELLED = 'CANCELLED'
}

// 任务接口
export interface AsyncTask {
  id: string
  type: string
  title: string
  status: TaskStatus
  progress: number
  message: string
  bookId?: number
  result?: any
  error?: string
  createdAt: Date
  updatedAt: Date
}

// 任务管理服务
class TaskManagerService {
  private tasks = ref<Map<string, AsyncTask>>(new Map())
  private registerTaskCallback: any
  private unregisterTaskCallback: any
  
  constructor() {
    const webSocketService = useWebSocketVue()
    this.registerTaskCallback = webSocketService.registerTaskCallback
    this.unregisterTaskCallback = webSocketService.unregisterTaskCallback
  }

  // 获取所有任务
  get allTasks() {
    return Array.from(this.tasks.value.values())
  }

  // 获取活跃任务（非完成状态）
  get activeTasks() {
    return this.allTasks.filter(task => 
      task.status === TaskStatus.PENDING || 
      task.status === TaskStatus.RUNNING
    )
  }

  // 获取任务
  getTask(id: string): AsyncTask | undefined {
    return this.tasks.value.get(id)
  }

  // 创建任务
  createTask(
    id: string,
    type: string,
    title: string,
    bookId?: number
  ): AsyncTask {
    const now = new Date()
    const task: AsyncTask = {
      id,
      type,
      title,
      status: TaskStatus.PENDING,
      progress: 0,
      message: '准备中...',
      bookId,
      createdAt: now,
      updatedAt: now
    }

    this.tasks.value.set(id, task)
    this.registerTaskCallback(type, id, this.handleTaskMessage.bind(this))
    
    return task
  }

  // 更新任务
  updateTask(id: string, updates: Partial<AsyncTask>): boolean {
    const task = this.tasks.value.get(id)
    if (!task) return false

    Object.assign(task, updates, { updatedAt: new Date() })
    this.tasks.value.set(id, { ...task })
    return true
  }

  // 删除任务
  removeTask(id: string): boolean {
    const task = this.tasks.value.get(id)
    if (!task) return false

    // 取消注册回调
    this.unregisterTaskCallback(task.type, id)
    return this.tasks.value.delete(id)
  }

  // 清理已完成/失败的任务
  cleanupCompletedTasks(): number {
    let count = 0
    const now = new Date()
    
    this.tasks.value.forEach((task, id) => {
      // 删除超过5分钟的已完成或失败任务
      const isOld = (now.getTime() - task.updatedAt.getTime()) > 5 * 60 * 1000
      if (isOld && (task.status === TaskStatus.COMPLETED || task.status === TaskStatus.FAILED)) {
        this.removeTask(id)
        count++
      }
    })
    
    return count
  }

  // 处理任务消息
  private handleTaskMessage(msg: UnifiedTaskMessage) {
    const taskId = msg.taskId
    if (!taskId) return

    const task = this.tasks.value.get(taskId)
    if (!task) return

    const updates: Partial<AsyncTask> = {}

    // 更新进度
    if (msg.progress !== undefined && msg.progress !== null) {
      updates.progress = msg.progress
    }

    // 更新消息
    if (msg.message) {
      updates.message = msg.message
    }

    // 更新状态
    if (msg.status === 'COMPLETED') {
      updates.status = TaskStatus.COMPLETED
      updates.progress = 100
      updates.message = '任务完成'
      // 注意：UnifiedTaskMessage接口中没有result属性
      
      // 调用完成回调
      const callbacks = (task as any).callbacks
      if (callbacks && callbacks.onComplete) {
        callbacks.onComplete() // 不传递result参数，因为接口中没有定义
      }
    } else if (msg.status === 'FAILED') {
      updates.status = TaskStatus.FAILED
      updates.error = msg.message || '任务失败'
      
      // 调用错误回调
      const callbacks = (task as any).callbacks
      if (callbacks && callbacks.onError) {
        callbacks.onError({ message: msg.message || '任务失败' })
      }
    } else if (msg.status === 'RUNNING') {
      updates.status = TaskStatus.RUNNING
    } else if (msg.status === 'CANCELLED') {
      updates.status = TaskStatus.CANCELLED
      
      // 调用取消回调
      const callbacks = (task as any).callbacks
      if (callbacks && callbacks.onCancel) {
        callbacks.onCancel()
      }
    }

    this.updateTask(taskId, updates)
  }
}

// 创建单例实例
export const taskManager = new TaskManagerService()

// 导出任务管理相关的组合式函数
export function useTaskManager() {
  return {
    get tasks() {
      return taskManager.allTasks
    },
    get activeTasks() {
      return taskManager.activeTasks
    },
    getTask: taskManager.getTask.bind(taskManager),
    createTask: taskManager.createTask.bind(taskManager),
    updateTask: taskManager.updateTask.bind(taskManager),
    removeTask: taskManager.removeTask.bind(taskManager),
    cleanupCompletedTasks: taskManager.cleanupCompletedTasks.bind(taskManager),
    addTask: (taskOptions: {
      id: string
      type: string
      title: string
      message: string
      bookId?: number
      onComplete?: (result: any) => void
      onError?: (error: any) => void
      onCancel?: () => void
    }) => {
      // 创建任务
      const task = taskManager.createTask(taskOptions.id, taskOptions.type, taskOptions.title, taskOptions.bookId)
      
      // 设置初始消息
      taskManager.updateTask(taskOptions.id, { message: taskOptions.message })
      
      // 存储回调函数
      if (taskOptions.onComplete || taskOptions.onError || taskOptions.onCancel) {
        (task as any).callbacks = {
          onComplete: taskOptions.onComplete,
          onError: taskOptions.onError,
          onCancel: taskOptions.onCancel
        }
      }
      
      return task
    }
  }
}